package com.jumi.microservice.service.logistics.express;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.dto.logistics.Logistics;
import com.jumi.microservice.dto.logistics.LogisticsSearchRequest;
import com.jumi.microservice.dto.logistics.LogisticsSearchResponse;
import com.sto.link.request.LinkRequest;
import com.sto.link.util.LinkUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author by mazhao
 * 百世快递
 * @Classname BestExpress
 * @Description TODO
 * @Date 2020/8/21 14:30
 */
@Service
public class StoExpress extends ResponseController implements Express {

    private static final Logger log = LoggerFactory.getLogger(StoExpress.class);

    /**
     * 测试环境
     * TODO
     */
//    private String url  = "http://cloudinter-linkgatewaytest.sto.cn/gateway/link.do";
    /**
     * 正式环境
     */
    private static String url = "https://cloudinter-linkgatewayonline.sto.cn/gateway/link.do";

    private static String api_name = "STO_TRACE_QUERY_COMMON";
    private static String from_appkey = "CAKKpMClFwfzMbk";
    private static String from_code = "CAKKpMClFwfzMbk";
    private static String to_appkey = "sto_trace_query";
    private static String to_code = "sto_trace_query";
    private static String secretKey = "0Xwe4TXycJFGR3PcF34LunTHJSd2Fe4h";

    @Override
    public String expressCode() {
        return "STO";
    }

    @Override
    public LogisticsSearchResponse logisticsSearch(LogisticsSearchRequest request) {
        log.info("申通快递查询参数[{}]", JSON.toJSONString(request));
        JSONArray jsonArray = new JSONArray();
        try {
            LinkRequest data=new LinkRequest();
            data.setFromAppkey(from_appkey);
            data.setFromCode(from_code);
            data.setToAppkey(to_appkey);
            data.setToCode(to_code);
            data.setApiName(api_name);
            JSONObject jsonObject = new JSONObject();
            List<String> ll = new ArrayList<>();
            ll.add(request.getLogisticsNo());
            jsonObject.put("waybillNoList",ll);
            data.setContent(jsonObject.toJSONString());
            String res = LinkUtils.request(data,url,secretKey);
            log.info("请求返回结果[{}]",res);
            jsonArray = JSONObject.parseObject(res).getJSONObject("data").getJSONArray(request.getLogisticsNo());
        } catch (Exception e) {
            log.error("申通快递查询出错[{}]",e.getMessage());
        }
        LogisticsSearchResponse logisticsSearchResponse = checkResult(jsonArray,request);
        return controller(logisticsSearchResponse,jsonArray,"memo","opTime");
    }

}
